package com.byron.pss.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * JDBC的工具类
 * @author Byron
 *
 */
public class JdbcUtils {

	private static Properties p = null;
	static {
		try {
			InputStream in = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("db.properties");
			p = new Properties();
			p.load(in);
			// 加载数据库驱动
			Class.forName(p.getProperty("driverClassName"));
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取数据库连接
	 * @return 数据库连接
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(p.getProperty("url"),
				p.getProperty("username"), p.getProperty("password"));
	}

	/**
	 * 关闭资源
	 * @param rs 
	 * @param ps
	 * @param conn
	 */
	public static void close(ResultSet rs, Statement ps, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (ps != null) {
					ps.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (conn != null) {
						conn.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
